import { useRequest as useRequestOrigin } from 'vue-request';
import { Message } from 'element-ui';
import { useWatch } from '@/hooks/useWatch.js';
const useResHandler = res => {
  return res?.data ? res.data : res;
};

// const ErrorMsgMap = {
//   401: '认证错误',
//   403: '您的请求被拒绝',
//   404: '您所请求的资源无法找到',
//   405: '您的请求被禁止',
// };
const useErrorHandler = error => {
  if (error?.message) {
    let reMsg;
    if (error.message === 'Network Error') {
      reMsg = '网络错误，请检查您的网络';
    } else if (error.message.includes('timeout')) {
      reMsg = '系统接口请求超时';
    } else if (error.message.includes('Request failed with status code')) {
      reMsg = '系统接口' + error.message.substr(error.message.length - 3) + '异常';
    }
    Message.error(reMsg);
  } else {
    Message.error(error.msg);
  }
  return error;
};
export const useRequest = (service, options) => {
  const res = ref(null);
  const { data, loading, run, error, params, refresh } = useRequestOrigin(service, options);
  useWatch(data, n => {
    res.value = n;
    if (n.code === 200) res.value = useResHandler(n);
    // if (n.code === 200) {
    //   res.value = useResHandler(n);
    // } else {
    //   useErrorHandler(n);
    // }
  });
  // useWatch(error, n => {
  //   useErrorHandler(n);
  // });
  return [res, loading, run, params, error, refresh];
};
